package com.yudaxian.sys.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.extra.tokenizer.TokenizerUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.yudaxian.common.HoneyLogs;
import com.yudaxian.common.util.IpUtils;
import com.yudaxian.common.util.JwtUtil;
import com.yudaxian.sys.entity.Logs;
import com.yudaxian.sys.entity.User;
import com.yudaxian.sys.service.ILogsService;
import com.yudaxian.sys.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogsAspect {

    @Resource
    private ILogsService logsService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserServiceImpl userService;

    @AfterReturning(pointcut = "@annotation(honeyLogs)")
    public void recordLog(HoneyLogs honeyLogs) {
        // 获取当前登录的用户的信息

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("X-Token");
        User loginUser;
        if (token == null) {
            String redisToken = userService.getCurrentToken();
            loginUser = (User) redisTemplate.opsForValue().get(redisToken);
        } else {
            loginUser = jwtUtil.parseToken(token, User.class);

        }
        if (loginUser == null) {
            log.error("记录日志信息报错，未获取到当前操作用户信息");
            return;
        }

        // 获取HttpServletRequest对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request2 = servletRequestAttributes.getRequest();

        // 获取到请求的ip
        String ip = IpUtils.getIpAddr(request2);
        Logs logs = Logs.builder()
                .operation(honeyLogs.operation())
                .type(honeyLogs.type().getValue())
                .ip(ip)
                .username(loginUser.getUsername())
                .time(DateUtil.now())
                .build();

        ThreadUtil.execAsync(() -> {
            // 异步记录日志信息
            logsService.addLogs(logs);
        });
    }

}
